﻿using Magicodes.Logger;
using Magicodes.Logger.NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Linq;

namespace TXH.DataSync.Helper
{
    public static class TaskHelper
    {
        public static LoggerBase Logger = new NLogLogger("TaskHelper");
        public static bool Start()
        {
            var flag = true;
            var logStr = string.Format("有{0}个表需要同步，即将处理...", ConfigHelper.ConfigInfo.TableReaders.Count);
            Console.WriteLine(logStr);
            Logger.Log(LoggerLevels.Debug, logStr);
            foreach (var tableSettings in ConfigHelper.ConfigInfo.TableReaders)
            {
                if (string.IsNullOrWhiteSpace(tableSettings.TableName))
                {
                    logStr = "有一个表配置没有设置表名，已跳过！";
                    Console.WriteLine(logStr);
                    Logger.Log(LoggerLevels.Error, logStr);
                    flag = false;
                    continue;
                }

                logStr = "正在准备同步【" + tableSettings.TableName + "】，WhereSql:" + tableSettings.WhereSql;
                Console.WriteLine(logStr);
                Logger.Log(LoggerLevels.Debug, logStr);

                try
                {
                    #region 读取数据
                    var dt = DbHelper.Query("Select * from " + tableSettings.TableName + " " + (string.IsNullOrWhiteSpace(tableSettings.WhereSql) ? "" : "where " + tableSettings.WhereSql)).ToDataTable();

                    logStr = "【" + tableSettings.TableName + "】数据获取成功，行数:" + dt.Rows.Count;
                    Console.WriteLine(logStr);
                    Logger.Log(LoggerLevels.Debug, logStr);
                    #endregion

                    if (dt.Rows.Count == 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        logStr = "【" + tableSettings.TableName + "】远程同步已经完成，没有需要同步的数据！";
                        Console.WriteLine(logStr);
                        Logger.Log(LoggerLevels.Debug, logStr);
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        continue;
                    }
                    
                    #region 序列化数据
                    var dataStr = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
                    logStr = "【" + tableSettings.TableName + "】数据内容:" + dataStr;
                    Logger.Log(LoggerLevels.Debug, logStr);
                    #endregion

                    #region 调用接口，同步数据
                    //请求接口
                    var result = ApiHelper.Post(tableSettings.TableName, dataStr);
                    if (result)
                    {
                        logStr = "【" + tableSettings.TableName + "】远程同步已经完成！";
                        Console.WriteLine(logStr);
                        Logger.Log(LoggerLevels.Debug, logStr);
                        #region 回写数据库
                        logStr = "【" + tableSettings.TableName + "】正在准备回写数据库标识！";
                        Console.WriteLine(logStr);
                        Logger.Log(LoggerLevels.Debug, logStr);

                        try
                        {
                            if (string.IsNullOrWhiteSpace(tableSettings.UpdateSetSqlWhenSuccess))
                            {
                                logStr = "同步【" + tableSettings.TableName + "】任务在回写数据时，发现配置错误：UpdateSetSqlWhenSuccess未设置！";
                                Console.WriteLine(logStr);
                                Logger.Log(LoggerLevels.Error, logStr);
                                flag = false;
                                continue;
                            }
                            if (string.IsNullOrWhiteSpace(tableSettings.UpdateSqlWhenSuccess))
                            {
                                logStr = "同步【" + tableSettings.TableName + "】任务在回写数据时，发现配置错误：UpdateSqlWhenSuccess未设置！";
                                Console.WriteLine(logStr);
                                Logger.Log(LoggerLevels.Error, logStr);
                                flag = false;
                                continue;
                            }

                            if (!DbHelper.Update(tableSettings.TableName, tableSettings.UpdateSetSqlWhenSuccess, tableSettings.UpdateSqlWhenSuccess))
                            {
                                logStr = "同步【" + tableSettings.TableName + "】任务在回写数据时，未获取到匹配的数据！";
                                Console.WriteLine(logStr);
                                Logger.Log(LoggerLevels.Error, logStr);
                                flag = false;
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            logStr = "同步【" + tableSettings.TableName + "】任务在回写数据时出现异常:" + ex.ToString();
                            Console.WriteLine(logStr);
                            Logger.Log(LoggerLevels.Error, logStr);
                            flag = false;
                            continue;
                        }

                        logStr = "同步【" + tableSettings.TableName + "】任务回写数据库标识已经成功完成！";
                        Console.WriteLine(logStr);
                        Logger.Log(LoggerLevels.Debug, logStr);
                        #endregion
                    }
                    else
                    {
                        flag = false;
                    }
                    #endregion


                }
                //catch (System.Data.SqlClient.SqlException sqlEx)
                //{
                //    logStr = "同步【" + tableSettings.TableName + "】时出现异常:" + sqlEx.ToString();
                //    Console.WriteLine(logStr);
                //    Logger.Log(LoggerLevels.Error, logStr);
                //}
                catch (Exception ex)
                {
                    logStr = "同步【" + tableSettings.TableName + "】时出现异常:" + ex.ToString() + "\n" + (ex.InnerException != null ? ex.InnerException.ToString() : string.Empty);
                    Console.WriteLine(logStr);
                    Logger.Log(LoggerLevels.Error, logStr);

                    logStr = "同步【" + tableSettings.TableName + "】时出现问题，已中断执行，具体异常请查看错误日志。";
                    Logger.Log(LoggerLevels.Debug, logStr);
                    flag = false;
                }

            }
            return flag;
        }
    }
}
